<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="fr" @click="exportData" :loading="exportLoading">导出</el-button>
    <div class="filter-container" style="flex-wrap: wrap">
      <el-date-picker class="filter-item" style="width: 230px;" v-model="query.daterange" type="daterange"
        value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="datePickerOption">
      </el-date-picker>
      <el-select class="filter-item" style="width: 200px;" v-model="query.plant" placeholder="选择工厂" filterable
        clearable>
        <el-option v-for="(item,index) in options.plant" :key="index" :label="item.plant_name" :value="item.plant_name">
        </el-option>
      </el-select>
      <el-input class="filter-item" style="width: 260px;" clearable v-model="query.queryString"
        placeholder="工站/品号/品名/规格/简码"></el-input>
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns">
      <template v-slot:content="v">
        <span v-if="v.key==='yield_rate'"><span :class="v.row.statusClass"
            style="width: 80px">{{v.row[v.key]}}</span></span>
        <span v-else>{{v.row[v.key]}}</span>
      </template>
    </z-table>
    <pagination v-show="total>0" :total="total" :page.sync="query.page" :limit.sync="query.size"
      @pagination="getList" />
  </div>
</template>

<script>
import { arrayToObject, dateTools, deepClone } from '@/utils'
import Pagination from '@/components/Pagination'
import _ from 'lodash'
import zTable from '@/views/_common/table'
import dayjs from 'dayjs'

const statusClass = { 0: 'bg-green', 1: '' }
const emptyData = {}
const defaultQurey = {
  plant: '',
  plan_start: '',
  plan_end: '',
  queryString: '',
}
export default {
  name: 'dailyPlanOutput',
  components: { Pagination, zTable },
  data: function () {
    return {
      name: '计划产出报表',
      api: this.$api.dailyplan,
      pageLoading: false,
      exportLoading: false,
      query: {
        page: 1,
        size: 10,
        ...defaultQurey,
      },
      list: [],
      exprotList: [],
      total: 0,
      options: { plant: [] },
      datePickerOption: {
        shortcuts: [
          {
            text: '最近30天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '当月',
            onClick(picker) {
              let today = dateTools.FormatDate()
              const end = today
              const start = dateTools.first_day(today)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '上月',
            onClick(picker) {
              let today = dateTools.FormatDate()
              const start = dateTools.first_day(dateTools.add_month(today, -1))
              const end = dateTools.last_day(start)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '上上月',
            onClick(picker) {
              let today = dateTools.FormatDate()
              const start = dateTools.first_day(dateTools.add_month(today, -2))
              const end = dateTools.last_day(start)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
      tableProps: {
        border: true,
        hideOperations: true,
      },
      columns: [
        { title: '计划日期', key: 'plan_date', width: 140, fixed: 'left' },
        { title: '工厂', key: 'plant_name', width: 120, fixed: 'left' },
        { title: '工段', key: 'section_name', width: 90, fixed: 'left' },
        { title: '工序', key: 'group_name', width: 90, fixed: 'left' },
        { title: '简码', key: 'brief_code', width: 60 },
        { title: '产品编码', key: 'sku_no', width: 110 },
        { title: '产品名称', key: 'sku_name', width: 140 },
        { title: '产品规格', key: 'sku_spec', width: 160 },
        { title: '课时', key: 'class_name', width: 100 },
        { title: '课时目标', key: 'class_output_target', width: 70 },
        { title: '课时良品产出', key: 'class_output', width: 100 },
        { title: '首次不良数', key: 'fail_qty', width: 90 },
        { title: '重复过站', key: 'repass_qty', width: 80 },
        { title: '二次不良数', key: 'refail_qty', width: 90 },
        { title: '总产出', key: 'total_pass', width: 70 },
        { title: '总不良', key: 'total_fail', width: 70 },
        { title: '良率目标', key: 'yield_rate_target', width: 80 },
        { title: '良率', key: 'yield_rate', width: 90 },
      ],
    }
  },
  methods: {
    getList() {
      this.pageLoading = true
      this.$request(this.api + 'getlist', this.formatQuery(this.query))
        .then((r) => {
          this.pageLoading = false
          this.list = this.formatData(r.list)
          this.total = r.total
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    research() {
      this.query.page = 1
      this.total = 0
      this.list = []
      this.getList()
    },
    formatQuery(query, nopage = false) {
      let tmp = deepClone(query)
      if (tmp.daterange) {
        tmp.plan_start = tmp.daterange[0]
        tmp.plan_end = tmp.daterange[1]
        delete tmp.daterange
      }
      if (nopage) {
        delete tmp.page
      }
      return tmp
    },
    formatData(data) {
      return data.map((item) => {
        let tmp = { ...item }
        if (tmp.yield_rate < tmp.yield_rate_target) {
          tmp.statusClass = 'text-red'
        } else {
          tmp.statusClass = 'text-green'
        }
        tmp.yield_rate = _.round(tmp.yield_rate * 100, 4) + '%'
        tmp.yield_rate_target = _.round(tmp.yield_rate_target * 100, 4) + '%'
        return tmp
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }),
      )
    },
    exportData() {
      let url = this.api
      let query = this.formatQuery(this.query, true)
      query.page = 1
      query.size = 99999
      this.exportLoading = true
      this.$request(url, query)
        .then((r) => {
          var exprotList = this.formatData(r.list)
          import('@/vendor/Export2Excel').then((excel) => {
            const filterVal = this.columns.map((item) => {
              return item.key
            })
            const tHeader = this.columns.map((item) => {
              return item.title || item.key
            })
            const data = exprotList.map((v) => filterVal.map((j) => v[j]))
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.name + '_' + dayjs().format('YYYYMMDD'),
            })
          })
        })
        .finally(() => {
          this.exportLoading = false
        })
    },
  },
  created: function () {
    this.$request(this.$api.plant + 'getlist').then((r) => {
      this.options.plant = r
    })
  },
}
</script>

<style scoped>
</style>
